package logic

import (
	"camera/C/Rpc/camera"
	"camera/C/Rpc/internal/svc"
	"camera/C/Rpc/model/mysql"
	"camera/C/Rpc/model/redis"
	"camera/C/Rpc/pkg"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *camera.LoginRequest) (*camera.LoginResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Rdb.Get(context.Background(), "smslogin"+in.Phone)
	if get.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	u := mysql.User{}
	err := u.GetUser(in.Phone)
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	if u.Phone == "" {
		u = mysql.User{
			Phone:    in.Phone,
			Password: pkg.PwdMd5(in.Password),
			Status:   1,
		}
		err = u.Create()
		if err != nil {
			return nil, fmt.Errorf("添加失败")
		}
	}
	if pkg.PwdMd5(in.Password) != u.Password {
		return nil, fmt.Errorf("密码错误")
	}
	return &camera.LoginResponse{
		Id: int64(u.ID),
	}, nil
}
